/**
 * Copyright © 2022 易久批信息技术有限公司. All rights reserved.
 */
package com.dysm.stream;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static java.lang.System.out;

/**
 *
 * @author xiay
 * @since 2022/4/5 11:18 下午
 */
public class StreamTest {

    public static void main(String[] args) {
        List<Item> items = Arrays.asList(
                new Item("apple", 10, new BigDecimal("9.99")),
                new Item("banana", 20, new BigDecimal("19.99")),
                new Item("orang", 10, new BigDecimal("29.99")),
                new Item("watermelon", 10, new BigDecimal("29.99")),
                new Item("papaya", 20, new BigDecimal("9.99")),
                new Item("apple", 10, new BigDecimal("9.99")),
                new Item("banana", 10, new BigDecimal("19.99")),
                new Item("apple", 20, new BigDecimal("9.99"))
        );

        // 按名称分组
        Map<String, List<Item>> collect1 = items.stream().collect(Collectors.groupingBy(Item::getName));
        out.println(collect1);

        // 按名称分组，统计每个分组列表数量
        Map<String, Long> collect2 = items.stream().collect(Collectors.groupingBy(Item::getName, Collectors.counting()));
        out.println(collect2);

        // 按名称分组，对count字段求和
        Map<String, Integer> collect3 = items.stream().collect(Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getCount)));
        out.println(collect3);

        // 按价格分组
        Map<BigDecimal, List<Item>> collect4 = items.stream().collect(Collectors.groupingBy(Item::getPrice));
        out.println(collect4);

        // 按价格分组，并且将名称转换成set集合
        Map<BigDecimal, Set<String>> collect5 = items.stream().collect(Collectors.groupingBy(Item::getPrice, Collectors.mapping(Item::getName, Collectors.toSet())));
        out.println(collect5);
    }
}

class Item {
    private String name;
    private Integer count;
    private BigDecimal price;
    Item(String name, Integer count, BigDecimal price) {
        this.name = name;
        this.count = count;
        this.price = price;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getCount() {
        return this.count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public BigDecimal getPrice() {
        return this.price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Item{" +
                "name='" + name + '\'' +
                ", count=" + count +
                ", price=" + price +
                '}';
    }
}
